package com.lmy.androidcustomview.view

import android.content.Context
import android.graphics.*
import android.os.Build
import android.util.AttributeSet
import android.view.View
import androidx.annotation.RequiresApi
import com.lmy.androidcustomview.R
import com.lmy.androidcustomview.toPx

/**
 * @author
 * @功能:圆形 图片 原理离屏缓冲
 * @Creat 2/8/21 5:00 PM
 * @Compony 465008238@qq.com
 */
class AvatarView(context: Context, attributeSet: AttributeSet) :View(context,attributeSet) {
   private val paint = Paint(Paint.ANTI_ALIAS_FLAG)
    private val IMAGE_WIDTH=200f.toPx
    private val IMAGE_PADDING=20f.toPx
    private val porterDuffXfermode=PorterDuffXfermode(PorterDuff.Mode.SRC_IN)
    private val bounds = RectF(IMAGE_PADDING, IMAGE_PADDING, IMAGE_PADDING + IMAGE_WIDTH, IMAGE_PADDING + IMAGE_WIDTH)
    @RequiresApi(Build.VERSION_CODES.LOLLIPOP)
    override fun onDraw(canvas: Canvas) {
        //设置离屏缓冲 离屏缓冲区域和矩形一样大 越小越好 因为耗资源
        val count = canvas.saveLayer(bounds, null)
        canvas.drawOval(IMAGE_PADDING,IMAGE_PADDING,IMAGE_PADDING+IMAGE_WIDTH,IMAGE_PADDING+IMAGE_WIDTH,paint)
        paint.xfermode = porterDuffXfermode
        canvas.drawBitmap(
            getAvatar(IMAGE_WIDTH.toInt()),
            IMAGE_PADDING,
            IMAGE_PADDING,
            paint
        )
        //恢复到离屏  之前的状态
        canvas.restoreToCount(count)
    }
    /**
     * 限制图片的大小
     */
    private fun getAvatar(width: Int):Bitmap {
        val options=BitmapFactory.Options()
        options.inJustDecodeBounds=true
        BitmapFactory.decodeResource(resources,
            R.drawable.ic_head, options)
        options.inJustDecodeBounds=false
        options.inDensity=options.outWidth
        options.inTargetDensity=width
        return BitmapFactory.decodeResource(resources,
            R.drawable.ic_head,options)
    }
}